package com.hsy.crm.web.config;

import com.hsy.crm.web.domain.po.login.LoginPo;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

public class ShiroAccessControlFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o){
        HttpServletRequest req = (HttpServletRequest) request;

        if( req.getRequestURI().indexOf("platform") != -1){
            return true;
        }

        // wait for delete
        if( req.getRequestURI().indexOf("demo") != -1){
            return true;
        }

        Subject subject = this.getSubject(request, response);

        boolean isAuthenticated = subject.isAuthenticated();
        if(isAuthenticated){

            String uri = req.getRequestURI();
            if( uri.indexOf("bussError") != -1){
                return true;
            }

            Object principal = subject.getPrincipal();
            if( principal == null ){
                return false;//? true or false?
            }

            //System.out.println("login:"+JsonUtils.toJson(principal));

            LoginPo login = (LoginPo) principal;
            String reqLoginUserId = req.getParameter("loginUserId");
            String reqCustomerId = req.getParameter("customerId");
            String reqCompanyId = req.getParameter("loginCompanyId");
            String reqCompanyLogicalCode = req.getParameter("loginCompanyLogicalCode");

            if( String.valueOf(login.getUserId()).equals(reqLoginUserId)
                    && login.getCustomerId().equals(reqCustomerId)
                    && String.valueOf(login.getCompanyId()).equals(reqCompanyId)
                    && login.getCompanyLogicalCode().equals(reqCompanyLogicalCode) ){
                return true;
            }else{
                return false;
            }
        }

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response){
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print("{\"result\":2}");
        out.close();
        return false;
    }
}
